import { Injectable } from '@nestjs/common';
import CreateUserDto from '../dto/CreateUserDto';
import { NacosNamingClientService } from 'libs/nacos/nacosNamingClient.service';
import actionBuilder from 'libs/common/utils/actionBuilder';
import User from '../entity/user.entity';

@Injectable()
export default class UserApi {
  private action = actionBuilder({
    timeout: 30 * 1000,
  });
  constructor(private nacosNamingClientService: NacosNamingClientService) {}

  private async getUserOneHostPath() {
    const host = await this.nacosNamingClientService.selectOneInstances({
      serviceName: 'user',
      groupName: 'DEFAULT_GROUP',
    });
    const path = 'http://' + host.ip + ':' + host.port;
    return path;
  }
  async createUser(createUserDto: CreateUserDto): Promise<string> {
    const path = await this.getUserOneHostPath();
    return await this.action({
      method: 'POST',
      url: '/user/create',
      data: createUserDto,
      baseURL: path,
    });
  }

  async getUserByEmail(email: string): Promise<User> {
    const path = await this.getUserOneHostPath();
    return await this.action({
      method: 'GET',
      url: '/user/getUserByEmail',
      params: {
        email,
      },
      baseURL: path,
    });
  }

  async getRoleKeysByUserId(userId: string): Promise<string[]> {
    const path = await this.getUserOneHostPath();
    return await this.action({
      method: 'GET',
      url: '/user/getRoleKeysByUserId',
      params: {
        userId,
      },
      baseURL: path,
    });
  }
}
